package com.siruier.boss.ui.fragment

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DividerItemDecoration
import com.aiyingli.ibxmodule.IBXSdk
import com.alibaba.fastjson.JSONObject
import com.ayl.deviceinfo.util.AllInfo
import com.ayl.deviceinfo.util.IMEIUtil
import com.siruier.boss.App
import com.siruier.boss.R
import com.siruier.boss.api.TASK_API_SERVICE
import com.siruier.boss.api.core.FirmException
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.taskApi
import com.siruier.boss.bean.AppTask
import com.siruier.boss.bean.TaskAppListParam
import com.siruier.boss.common.formatPriceRmb
import com.siruier.boss.databinding.ActivityBaseRefreshBinding
import com.siruier.boss.databinding.ItemTaskBinding
import com.siruier.boss.ui.AppCore
import com.siruier.boss.ui.activity.task.IbxTaskDetailActivity
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseFragment
import com.siruier.boss.ui.base.BaseRecyclerAdapter
import com.siruier.boss.ui.dialog.showAlertDialog
import com.siruier.boss.ui.ext.permissionRequest
import com.siruier.boss.ui.ext.startActivityExt
import com.siruier.boss.ui.ext.toColor
import com.siruier.boss.ui.ext.toastMessageLong
import com.siruier.boss.ui.helper.RefreshHelper
import com.siruier.boss.ui.utils.GlideUtils
import com.siruier.boss.utils.MiitmdidHelper
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

class CpaAsoFragment : BaseFragment<ActivityBaseRefreshBinding>() {

    private var mTaskAppListParam: TaskAppListParam? = null
    private var baseInit: Boolean = false
    private var isClickItem: Boolean = false
    private val mTaskAdapter = TaskAdapter()
    private lateinit var mRefreshHelper: RefreshHelper<AppTask>

    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        vb.titleView.isVisible = false
        vb.recyclerView.setBackgroundColor(R.color.white.toColor())
        mRefreshHelper = RefreshHelper(vb.refreshLayout, vb.recyclerView, mTaskAdapter, listener = ::onReload)
        vb.recyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        mTaskAdapter.setOnClickAdapterListenter(::onClick)
    }

    private fun onClick(view: View, position: Int) {
        isClickItem = true
        val appTask = mTaskAdapter.getItem(position)
        if (appTask.taskType == 0 && appTask.running == 0) {
            val intent = requireContext().packageManager.getLaunchIntentForPackage(appTask.appPackageName)
            if (intent != null) {
                "已安装[${appTask.appName}]请先卸载".toastMessageLong()
                return
            }
        }
        launchUI({
            mTaskAppListParam?.taskType = appTask.taskType
            mTaskAppListParam?.orderId = appTask.orderId
            mTaskAppListParam?.running = appTask.running
            val robTask = taskApi.robTask(mTaskAppListParam).toData()
            if (robTask?.otherTask == 0) {
                goDetail(robTask.url)
            } else {
                val giveUp = suspendCancellableCoroutine<Boolean> { coroutine ->
                    showAlertDialog {
                        mCancelable = false
                        message(message = "是否放弃当前任务\n并领取该任务")
                        negativeButton { coroutine.resume(false) }
                        positiveButton { coroutine.resume(true) }
                    }
                }
                if (giveUp) {
                    mTaskAppListParam?.taskId = robTask?.taskId
                    mTaskAppListParam?.taskType = robTask?.taskType
                    taskApi.giveUpTask(mTaskAppListParam).toData()

                    mTaskAppListParam?.orderId = appTask.orderId
                    mTaskAppListParam?.taskType = appTask.taskType
                    mTaskAppListParam?.running = 0
                    goDetail(taskApi.robTask(mTaskAppListParam).toData()?.url)
                } else {
                    // 取消  无事发生
                    return@launchUI
                }
            }
            mRefreshHelper.onRefresh()
        }, ApiObserver(context))
    }

    private fun goDetail(url: String?) {
        startActivityExt<IbxTaskDetailActivity> {
            putExtra("url", url)
        }
    }

    override fun initData(rootView: View?, savedInstanceState: Bundle?) {
        initDevice()
    }

    private fun initDevice() {
        launchUI({
            //  6.0 <= APP_TARGET_SDK_VERSION <= 9.0
            if (Build.VERSION_CODES.M <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                suspendCancellableCoroutine<Boolean> { coroutine ->
                    permissionRequest {
                        permission(Manifest.permission.READ_PHONE_STATE)
                        onDenied { coroutine.resumeWithException(FirmException("未授予读取IMEI权限无法做任务")) }
                        onGranted { coroutine.resume(true) }
                    }
                }
            } else {
                IBXSdk.getInstance().initApplication(AppCore.app)
                IBXSdk.getInstance().setOAIDInfo(
                    MiitmdidHelper.ASSET_FILE_NAME_CERT,
                    MiitmdidHelper.LIBRARY,
                    MiitmdidHelper.HELPER_VERSION_CODE
                )
            }
            val imei = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                IMEIUtil.getIMEI(AppCore.app)
            } else {
                App.OAID
            }
            if (imei == null) {
                throw FirmException("应用标识获取失败！")
            }
            val content = taskApi.taskContent(imei).toData()?.content
            val base = JSONObject()
            AllInfo.InfoBuilder(context).addClientId(content).allInfo.forEach {
                base.putAll(it.map)
            }
            mTaskAppListParam = TaskAppListParam(base, imei)
            baseInit = true
            appList()
        }, mRefreshHelper.handApiObserver())
    }

    private suspend fun appList(): MutableList<AppTask>? =
        TASK_API_SERVICE.appList(mTaskAppListParam).toData()?.records

    override fun onResume() {
        super.onResume()
        // 点击过一次详情才回到页面就刷新
        if (isClickItem) {
            onReload()
        }
    }

    private fun onReload() {
        if (baseInit) {
            launchUI({
                mTaskAppListParam?.currentPage = mRefreshHelper.page
                appList()
            }, mRefreshHelper.handApiObserver())
        } else {
            initDevice()
        }
    }
}

class TaskAdapter : BaseRecyclerAdapter<ItemTaskBinding, AppTask>() {

    override fun onBindViewHolder(vb: ItemTaskBinding, bean: AppTask, position: Int) {
        GlideUtils.intoView(vb.ivIcon.context, bean.appIcon, vb.ivIcon)
        vb.tvName.text = bean.appName
        vb.tvMoney.text = bean.price.formatPriceRmb() + bean.unit
        vb.tvTotalNum.text = "剩余：${bean.remainNum}"
        vb.tvRunning.text = if (bean.running == 1) {
            "进行中"
        } else {
            ""
        }
        setViewClick(position, vb.root)
    }
}